package com.bamanker.cloudsys.controller;

import com.bamanker.cloudsys.service.MyMailService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author bamanker
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class SmsController {

//    private static ConcurrentHashMap<String, Long> requestCountMap = new ConcurrentHashMap<>();

    private final MyMailService myMailService;

    @RequestMapping("/smsRec")
    @PreAuthorize("hasAuthority('web')")
    public String smsReceiver(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("code") String code) {
//        if (!limitRequestFrequency(request)) {
//            response.setStatus(429);
//            return "Too many requests";
//        } else {
        if (null != code) {

            log.info("收到消息，参数为：{}", code);
            String sub = "最新的验证码";
            myMailService.sendMail(sub, code);
            return "SENT OK!";
        }
//        }
        return "SENT FAIL";
    }

    @RequestMapping("/test")
    @PreAuthorize("hasAuthority('web')")
    public String testApi(HttpServletRequest request, HttpServletResponse response, @RequestParam("code") String code) {
//        if (!limitRequestFrequency(request)) {
//            response.setStatus(429);
//            return "Too many requests";
//        } else {
            if (null != code) {
                log.info("收到消息，参数为：{}", code);
                String sub = "最新的验证码";
                return "SENT OK!";
            }
//        }
        return "SENT FAIL";
    }

//    /**
//     * 接口防刷
//     * @param request
//     * @return
//     */
//    private boolean limitRequestFrequency(HttpServletRequest request) {
//        String ip = request.getRemoteAddr();
//        String uri = request.getRequestURI();
//        String key = ip + ":" + uri;
//        log.info("this request:{}", key);
//        Long lastRequestTime = requestCountMap.get(key);
//        long now = System.currentTimeMillis();
//        if (lastRequestTime != null && (now - lastRequestTime) < 5000) {
//            return false;
//        }
//        requestCountMap.put(key, now);
//        return true;
//    }
}
